<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, reactive, computed } from 'vue'
import * as echarts from 'echarts'
import { useRoute, useRouter } from 'vue-router'
import { mapStore } from '@/stores/worldMap'
import { headersStore } from '@/stores/apiHeader'
import { roleStore } from '@/stores/role'
import chinaJSON from './china.json'
import { useUserStore } from '@/stores/user'
import chianPoint from './chinaPoint'
import api from '@/api'
import { t } from '@/i18n'
const headStore = headersStore()
const theRoleStore = roleStore()
const { userInfo } = useUserStore() as any
const chartData = reactive({
  myChart: null,
  data: [],
})
// let scatter = chartData.data
const route = useRoute()
const router = useRouter()
const currentPath = router.currentRoute.value.path
const selectName = ref('') // 选择的省份

const inFoEarthData = async () => {
  const params = {
    scopeCode: ['0000111104'],
    bussinessCode: userInfo.bussinessCode,
    financeCode: userInfo.financeCode,
    supplyCode: userInfo.supplyCode,
    isMap: true, // 是否是地图
  }
  const res = await api.getInitEarthInfo(params)
  const { code, data } = res
  if (code == 0 && data) {
    const pointList = data.pointArray

    pointList.forEach((item) => {
      if (headStore.scope_code == item.scope_code) {
        selectName.value = item.province_name // 设置选择的省份
      }
      item['title'] = item.name
      item['isClick'] = item.isClick
      item['name'] =
        item.name + (item.perData != null ? '\n' + item.perData : '')
      item['value'] = [item.lon, item.lat, 9]
    })
    chartData.data = pointList
    drawChina()
  }
}

// chianPoint.forEach((item) => {
//   item['name'] = item.scopeName + '\n99'
//   item['value'] = [item.scopeLongitude, item.scopeLatitude, 9]
// })

const chinaMap = ref()
// onMounted(() => {
inFoEarthData()
// })
let regions = reactive([
  // {
  //   name: '新疆维吾尔自治区',
  //   itemStyle: {
  //     areaColor: '#374ba4',
  //     opacity: 1,
  //   },
  // },
  // {
  //   name: '四川省',
  //   itemStyle: {
  //     areaColor: '#fe9b45',
  //     opacity: 1,
  //   },
  // },
  // {
  //   name: '陕西省',
  //   itemStyle: {
  //     areaColor: '#fd691b',
  //     opacity: 1,
  //   },
  // },
  // {
  //   name: '黑龙江省',
  //   itemStyle: {
  //     areaColor: '#ffc556',
  //     opacity: 1,
  //   },
  // },
])

function drawChina() {
  chartData.myChart = echarts.init(chinaMap.value)
  echarts.registerMap('china', JSON.stringify(chinaJSON)) // 注册地图
  var option = {
    geo: {
      map: 'china',
      roam: true, //是否允许缩放，拖拽
      zoom: 1.5, //初始化大小
      //缩放大小限制
      scaleLimit: {
        min: 1, //最小
        max: 4, //最大
      },
      //设置中心点
      center: [106, 36],
      //省份地图添加背景
      regions: [
        {
          name: selectName.value,
          itemStyle: {
            areaColor: '#1940fb',
            opacity: 1,
          },
        },
      ],
      itemStyle: {
        areaColor: '#081545', // 地图背景色
        color: '#fff',
        borderColor: '#19c9fb', // 地图边框颜色
        borderWidth: 1, // 地图边框宽度
      },
      //高亮状态
      emphasis: {
        itemStyle: {
          areaColor: '#1940fb',
          color: '#fff',
        },
      },
    },
    //配置属性
    series: {
      name: 'chinaMap',
      type: 'effectScatter',
      coordinateSystem: 'geo',
      data: chartData.data,
      showEffectOn: 'render',
      rippleEffect: {
        //涟漪特效相关配置
        brushType: 'stroke', //波纹的绘制方式，可选 'stroke' 和 'fill'
      },
      hoverAnimation: true, //是否开启鼠标 hover 的提示动画效果
      label: {
        //图形上的文本标签，可用于说明图形的一些数据信息，比如值，名称等，

        formatter: '{b}',
        position: 'right',
        fontSize: '14px',
        color: '#feb636',
        show: true,
      },
      itemStyle: {
        //图形样式，normal 是图形在默认状态下的样式；emphasis 是图形在高亮状态下的样式，比如在鼠标悬浮或者图例联动高亮时

        color: '#fe732a', //散点的颜色
        shadowBlur: 10,
        shadowColor: 20,
        fontSize: '12px',
      },
      zlevel: 1,
    },
  }
  chartData.myChart.setOption(option)

  chartData.myChart.on(
    'click',
    { seriesName: 'chinaMap' },
    function (params: any) {
      if (params.data.isClick == true) {
        headStore.setScopeCode(params.data.scope_code)
        headStore.setEveryCode('') // 清空每个页面的code
        // 根据路由分配业务权限

        if (currentPath == '/home') {
          theRoleStore.setBusinessLevel(params.data.scope_level)
        }
        if (currentPath == '/finance') {
          theRoleStore.setFinanceLevel(params.data.scope_level)
        }
        if (currentPath == '/supply') {
          theRoleStore.setSupplyLevel(params.data.scope_level)
        }
        const province_name = params.data.province_name || '' // 省份名称
        selectName.value = province_name // 设置选中省份名称并高亮
        chartData.myChart.dispose() // 销毁地图
        drawChina() // 重绘地图
      } else {
        // 阻止重复弹窗
        const exchangeRateTips =
          document.getElementsByClassName('permissionTip')
        if (exchangeRateTips.length > 0) return
        const tipMsg = t('bi_common_youdonthavepermisson')
        ElMessage({
          message: tipMsg,
          offset: 300,
          showClose: true,
          duration: 1000,
          customClass: 'permissionTip',
        })
      }
    }
  )
}

const backBtnShow = computed(() => {
  return mapStore().isChina
})

/**
 * @description: 返回地球并重置数据
 */
const changeMap = () => {
  mapStore().setGlobalLoading(!mapStore().globalLoading)
  let mapType = false
  let level = 0
  let setLevelName = ''
  if (currentPath === '/home' && theRoleStore.businessLevel > 0) {
    headStore.setScopeCode(userInfo.bussinessCode[0])
    level = Number(userInfo.businessLevel)
    setLevelName = 'setBusinessLevel'
  } else if (currentPath === '/supply' && theRoleStore.supplyLevel > 0) {
    headStore.setScopeCode(userInfo.supplyCode[0])
    level = Number(userInfo.supplyLevel)
    setLevelName = 'setSupplyLevel'
  } else if (currentPath === '/finance' && theRoleStore.financeLevel > 0) {
    headStore.setScopeCode(userInfo.financeCode[0])
    level = Number(userInfo.financeLevel)
    setLevelName = 'setFinanceLevel'
  }

  theRoleStore[setLevelName](level)
  mapStore().setMapType(mapType)
  headStore.setEveryCode('')
}

// 销毁前释放内存
onBeforeUnmount(() => {
  if (chartData && chartData.myChart) {
    chartData.myChart.dispose()
  }
})
</script>

<template>
  <!-- 返回按钮 -->
  <el-button
    type="primary"
    class="map-btn"
    v-if="backBtnShow"
    @click="changeMap"
  >
    {{ $t('bi_front_distributorback') }}
  </el-button>
  <div ref="chinaMap" style="height: 100%; width: 100%" />
</template>

<style lang="scss" scoped>
.map-btn {
  position: absolute;
  top: 250px;
  left: 50%;
  transform: translate(-55%, 0);
  z-index: 12;
  background-color: rgba(11, 69, 202, 0.8);
}

.china-map {
  width: 100%;
  height: 100%;
}

.permissionTip {
  background-color: rgba(23, 96, 190, 0.65);
  border: #1e80ff solid 1px;

  .el-message-icon--info,
  .el-message__content,
  .el-message__closeBtn {
    color: #fff !important;
  }
}
</style>
